package com.leyou.search.mq;

import com.leyou.search.service.SearchService;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.ITEM_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.QueueConstants.SEARCH_ITEM_DOWN;
import static com.leyou.common.constants.MQConstants.QueueConstants.SEARCH_ITEM_UP;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.ITEM_DOWN_KEY;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.ITEM_UP_KEY;

/**
 * @author 虎哥
 */
@Component
public class ItemListener {

    private final SearchService searchService;

    public ItemListener(SearchService searchService) {
        this.searchService = searchService;
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = SEARCH_ITEM_UP, durable = "true"),
            exchange = @Exchange(name = ITEM_EXCHANGE_NAME, type = "topic"),
            key = ITEM_UP_KEY
    ))
    public void listenItemUp(Long id){
        if(id != null) {
            // 新增商品到索引库
            searchService.saveSpuById(id);
        }
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = SEARCH_ITEM_DOWN, durable = "true"),
            exchange = @Exchange(name = ITEM_EXCHANGE_NAME, type = "topic"),
            key = ITEM_DOWN_KEY
    ))
    public void listenItemDown(Long id){
        if(id != null) {
            // 删除指定的商品
            searchService.deleteSpuById(id);
        }
    }
}
